package cn.dugcrs.basic.interceptor;

import cn.dugcrs.basic.anno.PreAuthorize;
import cn.dugcrs.basic.jwt.JwtUtils;
import cn.dugcrs.basic.jwt.LoginSuccseeObj;
import cn.dugcrs.basic.jwt.Payload;
import cn.dugcrs.basic.jwt.RsaUtils;
import cn.dugcrs.system.mapper.PermissionMapper;
import cn.dugcrs.user.domain.Logininfo;
import cn.dugcrs.user.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.List;

import static cn.dugcrs.basic.jwt.JwtUtils.getInfoFromToken;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取token，不能为空
        String utoken = request.getHeader("token");
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        if(utoken == null || StringUtils.isEmpty(utoken)){
            // 获取登录失效或无法获取token，阻止放行 返回{"success":false,"resultObj":"noLogin"} 让前端跳到登录页面
            PrintWriter writer = response.getWriter();
            writer.write("{\"success\":false,\"resultObj\":\"noLogin\"}");
            writer.flush();
            writer.close();
            return false; // 阻止放行
        }
        // 获取登录信息
        Object loginTmp = redisTemplate.opsForValue().get(utoken);

        // 解密jwt字符串
        PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa.pub").getFile());
        Payload<LoginSuccseeObj> payload = getInfoFromToken(utoken, publicKey, LoginSuccseeObj.class);
        LoginSuccseeObj loginSuccseeObj = (LoginSuccseeObj)payload.getUserInfo();
        Logininfo logininfo = loginSuccseeObj.getLogininfo();
        // 如果是employee员工用户，需要校验权限
        if(logininfo.getType() == 0){
            // 拿到当前请求的URI，只关注带有@PreAuthorize方法
            HandlerMethod method = (HandlerMethod) handler;
            PreAuthorize preAuthorize = method.getMethodAnnotation(PreAuthorize.class);
            if(preAuthorize == null){
                return true; // 放行
            }
            // 当前访问方法的权限码，必须要检验登录人是否能访问它
            String sn = preAuthorize.value();
            // 登录人所拥有的按钮权限
            List<String> permissions = loginSuccseeObj.getPermissions();
            if(permissions.contains(sn)){ // 当前登录人拥有访问sn的权限
                return true; // 放行
            }
            // 没有权限，请联系管理员
            PrintWriter writer = response.getWriter();
            writer.write("{\"success\":false,\"resultObj\":\"noPermission\"}");
            writer.flush();
            writer.close();
            return false;//阻止
        }

        // 放行
        return true;
    }
}
